package com.twu.biblioteca.ui;

import com.twu.biblioteca.auth.Authenticator;

import java.util.HashMap;
import java.util.Map;

/**
 * This class represents a menu which contains multiple menu items.
 */
public class Menu {

    Map<String, MenuItem> menuShortcuts = new HashMap<String, MenuItem>();

    private Authenticator authenticator = new Authenticator();

    public Menu() {
    }

    public Menu(Authenticator authenticator) {
        this.authenticator = authenticator;
    }

    public void addItem(MenuItem menuItem) {
        if (menuItem == null) return;
        menuShortcuts.put(menuItem.getShortcut(), menuItem);
    }

    public void select(String shortcut) {
        MenuItem menuItem = menuShortcuts.get(shortcut);
        if (menuItem == null || !menuItem.isVisible(authenticator.isLoggedIn())) throw new InvalidMenuSelectionException();
        menuItem.select();
    }

    @Override
    public String toString() {
        String stringRep = "";
        for (MenuItem menuItem: menuShortcuts.values()) {
            if (menuItem.isVisible(authenticator.isLoggedIn())) {
                stringRep += String.format("%s >> %s\r\n", menuItem.getShortcut(), menuItem.getDescription());
            }
        }
        return stringRep;
    }

}
